package com.lcredu.seckill.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lcredu.seckill.pojo.User;
import com.lcredu.seckill.service.UserService;
import com.lcredu.seckill.util.CookieUtil;
import com.lcredu.seckill.util.response.RespBean;
import com.lcredu.seckill.util.response.RespBeanEnum;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.invoke.MethodHandle;
import java.util.concurrent.TimeUnit;

/**
 * @author 黎长容
 * @date 2025-09-13 16:46
 */
@Component
public class AccessLimitInterceptor implements HandlerInterceptor {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    /*
        1. 完成user对象的放置
        2. 完成对accessLimit的处理
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果他是作用在方法上
        if (handler instanceof HandlerMethod) {
            User user = getUser(request, response);
            //1. 存入user
            UserContext.setUser(user);
            //2. 完成对accessLimit的处理
            HandlerMethod hm = (HandlerMethod) handler;
            //对注解进行解析
            AccessLimit methodAnnotation = hm.getMethodAnnotation(AccessLimit.class);
            if (methodAnnotation == null) {
                return true;
            }
            int maxCount = methodAnnotation.maxCount();
            int second = methodAnnotation.second();
            boolean needLogin = methodAnnotation.needLogin();
            String uri = request.getRequestURI();
            if (needLogin) {
                if (user == null) {
                    //需要传入一个错误,但是这里还没写
                    render(response, RespBeanEnum.SESSION_ERROR);
                    return false;
                }
            }

            ValueOperations valueOperations = redisTemplate.opsForValue();
            String key = uri + ":" + user.getId();
            Integer count = (Integer) valueOperations.get(key);
            if (count == null) {
                valueOperations.set(key, 1, second, TimeUnit.SECONDS);
            } else if (count < maxCount) {
                valueOperations.increment(key);
            } else {
                //返回错误信息
                render(response, RespBeanEnum.REPEAT_CLICK);
                return false;
            }

        }

        return true;
    }

    //构建返回对象
    private void render(HttpServletResponse response, RespBeanEnum respBeanEnum) throws IOException {
        System.out.println("render--" + respBeanEnum.getMessage());
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        RespBean respBean = RespBean.error(respBeanEnum);
        writer.write(new ObjectMapper().writeValueAsString(respBean));
        writer.flush();
        writer.close();
    }

    private User getUser(HttpServletRequest request, HttpServletResponse response) {
        String userTicket = CookieUtil.getCookieValue(request, "userTicket");
        if (!StringUtils.hasText(userTicket)) {
            return null;
        }
        User user = userService.getUser(userTicket, request, response);
        return user;

    }
}
